package com.ascainiao.paygame.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ascainiao.paygame.JWTUtils;
import com.ascainiao.paygame.beans.ReturnData;
import com.ascainiao.paygame.mapper.TokenMapper;
import com.ascainiao.paygame.mapper.UserAdmin;
import com.ascainiao.paygame.mapper.UserAdminMapper;
import com.ascainiao.paygame.model.Token;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
public class UserAdminController {
    @Autowired
    private UserAdminMapper userAdminMapper;
    @Autowired
    private TokenMapper tokenMapper;

    @PostMapping("/user")
    public ReturnData getUserInfo(HttpServletRequest request){
        ReturnData rdata=new ReturnData();
        rdata.setStatusCode("fail");
        rdata.setMessage("登录失效");
        rdata.setData(null);
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("Admin-Token")){
                    String tokenStr = cookie.getValue();
                    QueryWrapper<Token> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("token", tokenStr);
                    List<Token> tokenList = tokenMapper.selectList(queryWrapper);
                    if(tokenList.size()==1){
                        Token tokenModel=tokenList.get(0);
                        JSONObject obj=JSON.parseObject(tokenModel.getData());
                        Map<String,String> map=new HashMap<>();
                        map.put("account",obj.getString("account"));
                        rdata.setStatusCode("success");
                        rdata.setMessage("成功");
                        rdata.setData(map);
                        return rdata;
                    }
                    /*try{
                        DecodedJWT decodedJWT = JWTUtils.decodeRsa(jwt);
                    }catch (SignatureVerificationException e){
                        System.out.println("无效签名");
                        rdata.setMessage("无效签名");
                        //e.printStackTrace();
                    }catch (TokenExpiredException e){
                        System.out.println("token已经过期");
                        rdata.setMessage("token已经过期");
                        //e.printStackTrace();
                    }catch (AlgorithmMismatchException e){
                        System.out.println("算法不一致");
                        rdata.setMessage("算法不一致");
                        //e.printStackTrace();
                    }catch (Exception e){
                        System.out.println("token无效");
                        rdata.setMessage("token无效");
                        //e.printStackTrace();
                    }*/
                    //rdata.setStatusCode("success");
                    //rdata.setMessage("成功");
                    rdata.setData(null);
                    return rdata;
                }
            }
        }
        return rdata;
        //List<UserAdmin> userList = userAdminMapper.selectList(null);
        //return userList;
    }
    @PostMapping("/salt")
    public ReturnData getSalt(@RequestParam String user_name){
        ReturnData rdata=new ReturnData();
        rdata.setStatusCode("fail");
        rdata.setMessage("失败");
        rdata.setData(null);
        String salt=userAdminMapper.selectSalt(user_name);
        if(salt!=""){
            rdata.setStatusCode("success");
            rdata.setMessage("成功");
            Map<String,String> map=new HashMap<>();
            map.put("salt",salt);
            rdata.setData(map);
        }
        return rdata;
    }
    @PostMapping("/login")
    public ReturnData login(@RequestParam String account, @RequestParam String password, @RequestParam String code, HttpServletRequest request){
        ReturnData rdata=new ReturnData();
        rdata.setStatusCode("fail");
        rdata.setMessage("登录失败");
        rdata.setData(null);
        //String code = requestMap.get("code").toString();
        String random = "";
        Token tokenModel;
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("Admin-Token")){
                    String tokenStr = cookie.getValue();
                    QueryWrapper<Token> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("token", tokenStr);
                    List<Token> tokenList = tokenMapper.selectList(queryWrapper);
                    if(tokenList.size()==1){
                        tokenModel=tokenList.get(0);
                        JSONObject obj=JSON.parseObject(tokenModel.getData());
                        random=obj.getString("code");
                        if (matchCaptcha(random.toUpperCase(),code.toUpperCase())) {
                            List<UserAdmin> users=userAdminMapper.selectUserAdmin(account,password);
                            if(users.size()==1){
                                UserAdmin ua = users.get(0);
                                obj.put("account",ua.getAccount());
                                tokenModel.setData(obj.toString());
                                queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("id",tokenModel.getId());
                                tokenMapper.update(tokenModel,queryWrapper);
                                rdata.setStatusCode("success");
                                rdata.setMessage("登录成功");
                                return rdata;
                            }
                            rdata.setMessage("账号或密码错误");
                            return rdata;
                        }
                        rdata.setMessage("验证码错误");
                        return rdata;
                    }
                }
            }
        }
        rdata.setMessage("token失效");
        return rdata;
    }
    private boolean matchCaptcha(String inputCaptcha, String storedCaptcha) {
        // 将输入的验证码和存储的验证码都转换为小写（或大写）
        String lowerCaseInput = inputCaptcha.toLowerCase();
        String lowerCaseStored = storedCaptcha.toLowerCase();

        // 比较两个验证码是否相同
        return lowerCaseInput.equals(lowerCaseStored);
    }
}
